import cv2
import numpy as np
import matplotlib.pyplot as plt
from slide import Direction


# 读取图像


def find_longest_prefix_match(img_orig, img_after, flip=False):
    '''
    找到两个图像的最长前缀匹配
    
    默认在 img_orig 中查找 img_after 的最长前缀匹配
    '''
    if flip:
        img_orig = cv2.flip(img_orig, 1)
        img_after = cv2.flip(img_after, 1)
        cv2.imwrite("flip.png", img_orig)
        cv2.imwrite("flip_orig.png", img_after)
    max_match_length = 0  # 最大匹配长度
    max_match_start = 0  # 最大匹配起始位置
    prefix_pointer = 0  # 匹配起始指针

    while prefix_pointer < img_orig.shape[1]:
        match_pointer = 0
        match_length = 0

        # 从当前前缀位置开始比较
        match_index = prefix_pointer
        while match_index < img_orig.shape[1] and match_pointer < img_after.shape[1]:
            if col_equal(img_orig, img_after, match_index, match_pointer):
                match_length += 1
                match_index += 1
            else:
                break
            match_pointer += 1

        # 如果找到更长的匹配，更新记录
        if match_length > max_match_length:
            max_match_length = match_length
            max_match_start = prefix_pointer

        # 移动前缀指针
        prefix_pointer += 1

    if max_match_length > 0:
        print(max_match_start, max_match_length)
        return img_orig[:, max_match_start: max_match_start + max_match_length + 1], img_after[:, :max_match_length], max_match_length
    else:
        return None, None


def pixel_similarity(column_A, column_B, threshold):
    # 计算两列的均方差
    column_A = column_A.astype(np.int32)
    column_B = column_B.astype(np.int32)
    me = np.mean(abs(column_A - column_B))

    # 如果均方差小于阈值，则认为像素值相似
    similar = me < threshold
    return similar


def col_equal(A, B, match_index, match_pointer):
    column_A = A[:, match_index]
    column_B = B[:, match_pointer]

    # 设置阈值，用于确定像素值相似性
    threshold = 10  # 调整此阈值以适应你的需求

    # 检查像素值相似性
    is_similar = pixel_similarity(column_A, column_B, threshold)

    return is_similar


def get_x_t(lst, direction):
    x_t = list()
    l = len(lst)
    if len(lst) <= 1:
        return lst
    for i in range(1, l):
        if (direction == Direction.Left and lst[i] < lst[i-1]) or (direction == Direction.Right and lst[i] > lst[i-1]):
            x_t.append(abs(lst[i] - lst[i-1]))
        else:
            x_t.append(0)
    print(x_t)
    return x_t


def count_speed(data, width):
    # 存储递增子数组的起始下标、中止下标和子数组本身的元组的列表
    increasing_subarrays = []

    # 当前递增子数组的起始和结束索引
    start = 0
    end = 0

    # 遍历数组
    for i in range(1, len(data)):
        if data[i] > data[i - 1]:
            # 如果当前元素大于前一个元素，则将结束索引后移
            end = i
        else:
            # 否则，当前递增子数组结束，将其添加到列表中
            if end > start:
                subarray = (start, end, data[start:end + 1])
                increasing_subarrays.append(subarray)
            # 更新起始索引为当前元素
            start = i
            end = i

    # 检查最后一个递增子数组是否需要添加
    if end > start:
        subarray = (start, end, data[start:end + 1])
        increasing_subarrays.append(subarray)

    # 打印递增子数组及其起始下标和中止下标
    for subarray in increasing_subarrays:
        start_index, end_index, subarray_data = subarray
        if end_index - start_index < 3:
            del subarray

    for subarray in increasing_subarrays:
        start_index, end_index, subarray_data = subarray
        print(f"Start Index: {start_index}, End Index: {end_index}, Subarray: {subarray_data}")

    array_length = len(increasing_subarrays)
    start_x = 999
    end_x = 0
    for i in range(1, array_length):
        start_index_1, end_index_1, subarray_data_1 = increasing_subarrays[i - 1]
        start_index_2, end_index_2, subarray_data_2 = increasing_subarrays[i]
        if start_index_2 - end_index_1 <= 2 and subarray_data_2[0] > subarray_data_1[-2]:
            for i in range(end_index_1, start_index_2):
                data[i] = 0
            start_x = min(start_x, start_index_1)
            end_x = max(end_x, end_index_2)
    print(data, start_x, end_x)
    test_date = data[start_x: end_x]
    print(test_date)
    x = range(len(test_date))

    # 绘制折线图
    plt.plot(x, test_date, marker='o')

    # 设置图表标题和坐标轴标签
    plt.title('Line Chart')
    plt.xlabel('Index')
    plt.ylabel('Value')

    # 显示图表
    plt.show()


# import os
# files = os.listdir("data/orig")
# findexs = []
# for file in files:


# img_orig = cv2.imread("5.png", cv2.IMREAD_GRAYSCALE)
# img_after = cv2.imread("4.png", cv2.IMREAD_GRAYSCALE)


# # 查找最长前缀匹配
# match,orig = find_longest_prefix_match(img_orig, img_after,False)

# if match is not None:
#     cv2.imwrite("match_image.png", match)
#     cv2.imwrite("orig_image.png", orig)
# else:
#     print("没有前缀匹配")
